<template>
	<view class="newDiseases">
		<navBar :title="titleName"></navBar>
		<view class="headLine">
			{{ subTitleName }}
		</view>
		<view class="Dlocation">
			<view class="required-form-item">*</view>
			<view class="">病害位置</view>
		</view>
		<!-- 站点类型为区间 -->
		<view class="formFill">
			<u-form labelPosition="left" :model="changeBefore" :rules="rules" ref="form1"
				v-if="lineInfo.lineSiteSectionType == 'qj'">
				<u-form-item label="环号" prop="" borderBottom ref="item1" labelWidth='100'>
					<view class="" style="display: flex;align-items: center;">
						<u--input type="number" class='change-input1' v-model="changeBefore.startNumber"
							@blur="blurs($event)" @change="changeVal($event, 3)"></u--input>~
						<u--input type="number" class='change-input2' v-model="changeBefore.endNumber"
							@blur="blurs($event)"
							@input="changeBefore.endNumber = changeBefore.endNumber.replace(/^(0+)|[^\d]+/g,'')"></u--input>
					</view>
				</u-form-item>
				<u-form-item label="开始里程" prop="" borderBottom ref="item1" labelWidth='100'>
					<view style="display: flex;align-items: center;">
						<view @click="chooseMileage" style="width: 320rpx;margin-right: 20rpx;">
							<u--input :disabled="true" class='change-input' inputAlign='center'
								v-model="value"></u--input>
						</view>
						<view class="" style="display: flex;align-items: center;">
							<u--input type="number" class='change-input1' v-model="changeBefore.startMileageFront"
								maxlength="4" @change="changeVal($event, 1)" @input="inputVal($event, 1)"></u--input>+
							<u--input type="number" class='change-input2' v-model="changeBefore.startMileageAfter"
								maxlength="4" @change="changeVal($event, 2)" @input="inputVal($event, 2)"></u--input>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="结束里程" prop="" borderBottom ref="item1" labelWidth='100'>
					<view style="display: flex;align-items: center;">
						<view style="width: 320rpx;margin-right: 20rpx;">
							<u--input :disabled="true" class='change-input' inputAlign='center'
								v-model="value"></u--input>
						</view>
						<view class="" style="display: flex;align-items: center;">
							<u--input type="number" class='change-input1' v-model="changeBefore.endMileageFront"
								maxlength="4">
							</u--input>+
							<u--input type="number" class='change-input2' v-model="changeBefore.endMileageAfter"
								maxlength="4">
							</u--input>
						</view>
					</view>
				</u-form-item>

				<u-form-item label="其他" prop="others" borderBottom ref="item1" labelWidth='100'>
					<u--input class='change-input3' v-model="changeBefore.others"></u--input>
				</u-form-item>
				<u-form-item label="时针位置" prop="clockwisePosition" ref="item1" labelWidth='100' @click='changtime'>
					<u--input class='change-input3' disabled disabledColor="#ffffff"
						v-model="changeBefore.clockwisePosition" suffixIcon="arrow-down">
					</u--input>
				</u-form-item>
			</u-form>
			<!-- 车站 -->
			<view class="add-station-box" style="margin-top: 40rpx;" v-if="lineInfo.lineSiteSectionType == 'cz'">
				<view class="flex-chezhan" @click="chooseEquip(1)">
					<view class="font-chezhan">车站位置</view>
					<view>
						<text style="font-size: 30rpx;padding-right: 16rpx;">{{changeBefore.stationLocation}}</text>
						<u-icon class='icon-disease' name="arrow-right"></u-icon>
					</view>
				</view>
				<view class="flex-chezhan">
					<view class="font-chezhan">其他</view>
					<view style="width: 70%;">
						<u--input class='change-input3'  border="surround" v-model="changeBefore.others"></u--input>
					</view>
				</view>
			</view>
			<!-- 其他站点 -->
			<view style="margin-top: 40rpx;"
				v-if="lineInfo.lineSiteSectionType !== 'qj' && lineInfo.lineSiteSectionType !== 'cz'">
				<view class="flex-chezhan">
					<view class="font-chezhan">位置</view>
					<view style="width: 70%;">
						<u--input class='change-input3'  border="surround" v-model="changeBefore.others">
						</u--input>
					</view>
				</view>
			</view>
		</view>

		<view class="content-colot"></view>
		<view class="d-remarks">
			<view class="d-text">
				<view class="txt-star">病害现状</view>
				<view class="">
					<u-button size="mini" color="#2f80ed" @click="diseaseJs">常用</u-button>
				</view>
			</view>
			<view class="form-item form-item-description">
				<u-textarea v-model="changeBefore.diseaseStatus" placeholder="请输入内容"
					@confirm="getDefineValue($event,'status')" confirmType='done'>
				</u-textarea>
				<record class="form-item-icon form-item-icon-voice" @setText="fnDescription($event,'status')"></record>
				<image v-if="changeBefore.diseaseStatus" mode="scaleToFill"
					class="form-item-icon form-item-icon-clear" src="/static/image/login/del1.png"
					@click="clearTxt($event, 'status')"></image>
			</view>
		</view>
		<view class="l-dsGrade">
			<view class="l-dsGrade-text">病害等级</view>
			<picker mode="multiSelector" :range="levelColumns" range-key="diseaseGrade" @cancel="fnlevelCancel"
				@columnchange="fnMultiColumnChange" @change="fnMultiPickerChange" :value="values">
				<!-- 可编辑等级 -->
				<view class="l-leave" @click="fnChooseLevel" v-if="changeBefore.diseaseStatus">
					{{ changeBefore.diseaseGrade || '' }}{{ changeBefore.diseaseNo || '' }}
					<u-icon class='icon-disease' name="arrow-right"></u-icon>
				</view>
			</picker>
		</view>

		<view class="content-colot"></view>
		<view class="swich-selection">
			<view class="selection-choose">
				<view class="choose-text">砂性土层</view>
				<view style="display: flex;align-items: center;">
					<u-switch v-model="changeBefore.isSandySoil" inactiveColor="rgb(230, 230, 230)"
						@change="swichChange1"></u-switch>
					<text style="margin-left: 20rpx;">{{changeBefore.isSandySoil ? "是" : "否"}}</text>
				</view>
			</view>
			<view class="selection-choose">
				<view class="choose-text">影响设备</view>
				<view style="display: flex;align-items: center;">
					<u-switch v-model="changeBefore.isInfluenceEquipment" inactiveColor="rgb(230, 230, 230)"
						@change="swichChange2"></u-switch>
					<text style="margin-left: 20rpx;">{{changeBefore.isInfluenceEquipment ? "是" : "否"}}</text>
				</view>
			</view>
			<view class="selection-choose" v-if="changeBefore.isInfluenceEquipment">
				<view class="choose-text">影响设备位置</view>
				<view class="add-case" v-if="compoType === 'add'"
					style="display: flex;align-items: center;justify-content: space-between;opacity: 0.8">
					<view v-if="changeBefore.deviceLocation === '其他'" style="width: 220rpx;margin-right: 30rpx;">
						<u--input maxlength="5" placeholder="请输入内容" border="surround" v-model="changeBefore.inputValue">
						</u--input>
					</view>
					<view @click="chooseEquip(2)">
						<text style="font-size: 30rpx;">{{changeBefore.deviceLocation}}</text>
						<u-icon class='icon-disease' name="arrow-right"></u-icon>
					</view>
				</view>
				<view class="other-case"
					style="display: flex;align-items: center;justify-content: space-between;opacity: 0.8"
					v-if="compoType==='modify' || compoType==='approval'">
					<view v-if="changeBefore.deviceLocation === '其他'" style="width: 220rpx;margin-right: 30rpx;">
						<u--input maxlength="5" placeholder="请输入内容" border="surround" v-model="changeBefore.inputValue">
						</u--input>
					</view>
					<view @click="chooseEquip(2)">
						<text style="font-size: 30rpx;">{{changeBefore.deviceLocation}}</text>
						<u-icon class='icon-disease' name="arrow-right"></u-icon>
					</view>
				</view>
			</view>
			<view class="selection-choose">
				<view class="choose-text">铁路保护区段</view>
				<view style="display: flex;align-items: center;">
					<u-switch v-model="changeBefore.isProtectionSection" inactiveColor="rgb(230, 230, 230)"
						@change="swichChange3"></u-switch>
					<text style="margin-left: 20rpx;">{{changeBefore.isProtectionSection ? "是" : "否"}}</text>
				</view>
			</view>
		</view>
		<view class="content-colot"></view>
		<view class="photo-list">
			<view class="photo-top">
				<view class="photo-text">病害照片</view>
			</view>
			<u-upload :fileList="fileListImg" @afterRead="afterRead" @delete="deletePic" name="Img" multiple
				:maxCount="9" :previewFullImage="true" accept="image"></u-upload>
		</view>
		<compressionImage></compressionImage>

		<!-- 视频开始 -->
		<view class="content-colot"></view>
		<commonVideoUpload :videoFileList="changeBefore.videoFileList" :playVideoSrc="playVideoSrc" @clickMedias="clickMedias"
			@handleClickPreview="handleClickPreview" @closePlayVideoSrc="playVideoSrc = ''"
			@closeFile="closeFile" class="no-warp"></commonVideoUpload>
		<!-- 视频结束 -->

		<view class="content-colot"></view>
		<view class="d-remarks">
			<view class="d-text">
				<view>修复措施</view>
				<view class="">
					<u-button size="mini" color="#2f80ed" @click="chooseRepair">常用</u-button>
				</view>
			</view>
			<view class="form-item form-item-description">
				<u-textarea v-model="changeBefore.repairMethod" placeholder="请输入内容"
					@confirm="getDefineValue($event,'methods')" @blur="inputBlur($event,'methods')" confirmType='done'>
				</u-textarea>
				<record class="form-item-icon form-item-icon-voice" @setText="fnDescription($event,'methods')"></record>
				<image v-if="changeBefore.repairMethod" mode="scaleToFill" class="form-item-icon form-item-icon-clear"
					src="/static/image/login/del1.png" @click="clearTxt($event, 'methods')"></image>
			</view>
		</view>
		<view class="patrol" v-if="compoType === 'modify' || compoType === 'approval'">
			<view>
				<view class="content-colot"></view>
				<view class="personnel">
					<view class="personnel-tit">巡查人员</view>
					<view class="personnel-nm">{{ changeBefore.inspectUser }}</view>
				</view>
				<view class="content-colot"></view>
				<view class="submit-event">
					<view class="submit-e">提交时间</view>
					<view class="submit-time">{{ getDate2(changeBefore.createDate) }}/{{ changeBefore.createUserName }}
					</view>
				</view>
			</view>
		</view>
		<u-picker :show="showTime" :columns="[columns]" title="时针位置" @cancel="cancel" @confirm="confirm">
		</u-picker>
		<view class="footer-button" v-if="compoType !== 'approval'">
			<view class="button-placeholder"></view>
			<view class="button-group">
				<button :loading="reqLoading" @click="submit" throttleTime="2000"   :disabled="isChooseImg" class="button-primary">{{textType}}</button>
			</view>
		</view>
		<view class="footer-button" v-else>
			<view class="button-placeholder"></view>
			<view class="button-group">
				<button  @click="show1 = true" class="button-warn">废弃</button>
				<button  @click="passBtn" class="button-primary" :disabled="isChooseImg" :loading="isChooseImg">通过</button>
			</view>
		</view>
		<view>
			<u-modal :show="show1" :content='content' @confirm="sureBtn" @cancel="()=>show1 = false"
				:showCancelButton='true' :buttonReverse="true" confirmText='是' cancelText='否' cancelColor='red'>
			</u-modal>
		</view>
		<!-- 影响设备选择器 -->
		<u-popup :show="isShowEquip">
			<view class="item-sel-box">
				<text style="padding-left: 50rpx" @click="cancelEquip(2)">取消</text>
				<text>影响设备位置</text>
				<text style="padding-right: 50rpx;color: #169bd5;" @click="sureEquip(2)">确定</text>
			</view>
			<u-grid :border="false" col="3" style="height: 600rpx; overflow-y: auto;">
				<u-grid-item v-for="(i,idx) in equipList" :key="i.id">
					<text class="item-equip" @click="clickItemBox(i,idx, 2)"
						:class="currentItemIndex === idx ? 'activeClass' : ''">{{i.name}}</text>
				</u-grid-item>
			</u-grid>
		</u-popup>

		<!--车站位置选择器 -->
		<u-popup :show="isShowStation">
			<view class="item-sel-box">
				<text style="padding-left: 50rpx" @click="cancelEquip(1)">取消</text>
				<text>位置选择</text>
				<text style="padding-right: 50rpx;color: #169bd5;" @click="sureEquip(1)">确定</text>
			</view>
			<u-grid :border="false" col="3" style="height: 400rpx; overflow-y: auto;">
				<u-grid-item v-for="(i,idx) in stationList" :key="i.id">
					<view class="item-equip" @click="clickItemBox(i,idx, 1)"
						:class="currentStationItemIndex === idx ? 'activeClass' : ''">{{i.name}}</view>
				</u-grid-item>
			</u-grid>
		</u-popup>
		<!-- 里程类别选择器 -->
		<view>
			<u-picker :show="isShowMileage" title="里程类别" :columns="mileageList" @confirm="sureMileage"
				@cancel="isShowMileage = false"></u-picker>
		</view>
	</view>
</template>

<script>
	import mixins from "@/utils/mixins.js"
	import {
		imgFun
	} from "@/utils/common.js";
	import {
		uploadFile,
		uploadVideoFile
	} from '@/utils/request'
	import {
		getToken
	} from '@/utils/auth.js'
	import {
		getPicture,
		deleteImg
	} from '@/api/doc.js' //获取图片
	import {
		diseaseGradeList,
		getDiseaseContent,
		getCalculateMileageLoop,
		lineSectionGet
	} from '@/api/engineeringMaintenance/engineeringMaintenance.js'
	import {
		dictionaryCache
	} from "@/utils/offline/cache.js"
	import {
		doGet,
		doSave,
		doDelete
	} from "@/utils/offline/sqlite/index.js";
	//巡检的所有接口
	import * as XUNJIAN from '@/api/engineeringMaintenance/engineeringMaintenance.js'
	import {
		getImageBase64
	} from "@/utils/imageOperation.js"
	import compressionImage from "@/components/compression-image/compression-image.vue";
	import permision from "@/js_sdk/wa-permission/permission.js"
	import {
		getPermission
	} from "@/utils/common.js"
	// #ifdef APP-PLUS
	import {
		DB
	} from "@/utils/offline/sqlite/dbinit.js";
	// #endif
	export default {
		name: 'ncDusease',
		mixins: [mixins],
		components: {
			compressionImage
		},
		props: {
			titleName: {
				type: String,
				default: ''
			},
			subTitleName: {
				type: String,
				default: ''
			},
			mileage: {
				type: String,
				default: ''
			},
			compoType: {
				type: String,
				default: ''
			},
			lineSiteSectionType:{
				type: String,
				default: ''
			},
			// changeBefore: {
			// 	type: Object,
			// 	default: () => ({})
			// },
			textType: {
				type: String,
				default: '确定'
			},
			value: {
				type: String,
				default: ''
			}
		},
		watch: {
			subTitleName(newV, oldV) {
				if (newV) {
					this.subTitleName = newV
				}
			},
			value: {
				handler(newVal) {
					console.log(newVal, '====376');
					this.$emit('input', newVal)
					if (newVal === 'SK' && newVal !== 'XK') {
						this.mileageList = [
							['SK', 'MK']
						]
					} else if (newVal === 'XK' && newVal !== 'SK') {
						this.mileageList = [
							['XK', 'MK']
						]
					}
					let name = this.subTitleName.substring(this.subTitleName.length - 2, this.subTitleName.length)
					console.log(name, '===');
					if (newVal === 'MK' && name === "上行") {
						this.mileageList = [
							['SK', 'MK']
						]
					} else if (newVal === 'MK' && name === "下行") {
						this.mileageList = [
							['XK', 'MK']
						]
					}
				},
				immediate: true,
				deep: true

			},
			"changeBefore.deviceLocation": {
				handler(newVal, oldVal) {
					if (newVal) {
						if (newVal.includes('其他')) {
							newVal = newVal.substring(newVal.length - 2, newVal.length)
						}
						this.equipList.forEach((it, index) => {
							if (it.name === newVal) {
								this.currentItemIndex = index
							}
						})
					}
				},
				immediate: true,
				deep: true
			},
			"changeBefore.stationLocation": {
				handler(newVal, oldVal) {
					if (newVal) {
						this.stationList.forEach((it, index) => {
							if (it.name === newVal) {
								this.currentStationItemIndex = index
							}
						})
					}
				},
				immediate: true,
				deep: true
			},
			"changeBefore.fileListImg": {
				handler(newVal, oldVal) {
					if (newVal) {
						this.fileListImg = newVal
					}
				},
				immediate: true,
				deep: true
			},
			"changeBefore.videoFileList": {
				handler(newVal, oldVal) {
					if (newVal) {
						this.changeBefore.videoFileList = newVal
					}
				},
				immediate: true,
				deep: true
			}
		},
		mounted() {
			this.$store.commit("setCompressionImageThis", this);
			this.getLevelOptions(uni.getStorageSync('isOwner'))
		},

		beforeDestroy() {
			this.$store.commit("setCompressionImageThis", null);
		},
		created() {
			this.lineInfo = JSON.parse(uni.getStorageSync('lineData'))
			this.ownerCode = uni.getStorageSync('ownerCode')
			this.equipList = this.$store.getters.dictMap['device_location']
			this.stationList = this.$store.getters.dictMap['station_location']
			console.log(this.equipList, '设备');
		},

		data() {
			return {
				reqLoading: false,
				show1: false,
				content: '废弃的病害将会删除或恢复到变更前，且不可恢复，是否确认？',
				formData: {},
				rules: {},
				showTime: false,
				columns: ['1点', '2点', '3点', '4点', '5点', '6点', '7点', '8点', '9点', '10点', '11点', '12点'],
				isChooseImg: false,
				isClickEnter: false, //是否自定义现状
				isShowEquip: false,
				isShowStation: false,
				equipList: [], //设备列表
				stationList: [],
				currentItemIndex: -1,
				currentStationItemIndex: -1,
				levelColumns: [
					[],
					[]
				],
				fileListImg: [],
				values: [0, 0],
				base_code: undefined, //base图片编码
				lineInfo: {}, //存储在本地的区间站点数据
				playVideoSrc: '',
				isShowMileage: false,
				mileageList: [],
				ownerCode: undefined, //用于区分厦门业主还是杭港业主
				testTimeArr: [],
				changeBefore: {
					videoFileList:[],
					removeFileSet:new Set()
				},
			}
		},
		methods: {
			//求两个数之间的数
			getNumbersInRange(num1, num2) {
			  const result = [];
			  const step = (num1 > num2) ? -1 : 1;

			  for (let i = num1; i !== num2 + step; i += step) {
			    result.push(i);
			  }

			  return result;
			},
			async blurs(e) {
				if (this.changeBefore.startNumber && this.changeBefore.endNumber) {
					// let _param = {
					// 	startLoop: this.changeBefore.startNumber,
					// 	endLoop: this.changeBefore.endNumber,
					// 	// lineSectionId:this.changeBefore.lineSiteSectionId
					// 	lineSectionId: this.lineInfo.lineSiteSectionId
					// }
					// let res = await getCalculateMileageLoop(_param)
					let response = await lineSectionGet({
						id: this.lineInfo.lineSiteSectionId 
					})
					if (response.result) {
						console.log(response, '响应--');
						let resultObj = response.result
						//算出录入的开始环号的对应里程信息  对应里程=开始里程+（录入环号-开始环号）*（开始里程-结束里程）/（开始环号-结束环号）
						//开始里程
						let startMileageTest = (resultObj.startMileageUp * 1000) + resultObj.startMileageBelow
						//结束里程
						let endMileageTest = (resultObj.endMileageUp * 1000) + resultObj.endMileageBelow
						//需要将这个结果四舍五入保留整数 然后再除以1000 分两段展示 sk+千位以上 + 千位以下 
						let TestStart = startMileageTest + ((this.changeBefore.startNumber) - resultObj.startLoop) * (
							startMileageTest - endMileageTest) / (resultObj.startLoop - resultObj.endLoop)
						let TestEnd = startMileageTest + ((this.changeBefore.endNumber) - resultObj.startLoop) * (
							startMileageTest - endMileageTest) / (resultObj.startLoop - resultObj.endLoop)
						console.log(startMileageTest, endMileageTest, TestStart, TestEnd, '开始，结束，开始对应，结束对应');
						/**
						 * 需要计算的情况(需要考虑两种情况 一种是正向巡查,eg:1--->4, 另一种是反向巡查，eg:4--->1)
						 * 正向情况（startLoop < endLoop）
						 * 1.输入的环号1和环号2与返回的值相等并且是返回值之间数的时候
						 * 2.环号1相等或者大于startLoop只需要计算开始里程
						 * 3.环号2相等或者小于endLoop只需要计算结束里程
						 * 反向情况 (startLoop > endLoop)
						 * 1.输入环号1 小于或者等于 startLoop 只需要计算开始里程
						 * 2.输入环号2大于或者等于endLoop只需要计算结束里程
						 */
						this.nextTick('startMileageFront', '')
						this.nextTick('startMileageAfter', '')
						this.nextTick('endMileageFront', '')
						this.nextTick('endMileageAfter', '')
						// console.log(this.getNumbersInRange(resultObj.startLoop, resultObj.endLoop).includes(Number(this.changeBefore.startNumber) || Number(this.changeBefore.endNumber)), '哈哈哈');
						// if(this.getNumbersInRange(resultObj.startLoop, resultObj.endLoop).includes(Number(this.changeBefore.startNumber) || Number(this.changeBefore.endNumber)))
						if (resultObj.startLoop < resultObj.endLoop) {

							if (this.getNumbersInRange(resultObj.startLoop, resultObj.endLoop).includes(Number(this.changeBefore.startNumber)) && this.changeBefore.startNumber >= resultObj.startLoop && TestStart > 1000) {
								const startUp = Number(Math.floor(Math.round(TestStart) / 1000))
								const startEnd = Math.round(Number(TestStart % 1000))

								this.nextTick('startMileageFront', startUp)
								this.nextTick('startMileageAfter', startEnd)
								// this.nextTick('endMileageFront', '')
								// this.nextTick('endMileageAfter', '')
								console.log('只需要计算开始里程', startUp, startEnd);
							}
							if (this.getNumbersInRange(resultObj.startLoop, resultObj.endLoop).includes(Number(this.changeBefore.endNumber)) &&  this.changeBefore.endNumber <= resultObj.endLoop &&  TestEnd > 1000) {
								const afterUp = Number(Math.floor(Math.round(TestEnd ) / 1000))
								const afterEnd = Math.round(Number(TestEnd % 1000))
								this.nextTick('endMileageFront', afterUp)
								this.nextTick('endMileageAfter', afterEnd)
								console.log('只需要计算结束里程', afterUp, afterEnd);
							}
						} else if (resultObj.startLoop > resultObj.endLoop) {
							if (this.getNumbersInRange(resultObj.startLoop, resultObj.endLoop).includes(Number(this.changeBefore.startNumber)) && this.changeBefore.startNumber <= resultObj.startLoop && TestStart > 1000) {
								const startUp = Number(Math.floor(Math.round(TestStart ) / 1000))
								const startEnd = Math.round(Number(TestStart % 1000))
								this.nextTick('startMileageFront', startUp)
								this.nextTick('startMileageAfter', startEnd)
								console.log('反向情况只需要计算开始里程', startUp, startEnd);
							}
							if (this.getNumbersInRange(resultObj.startLoop, resultObj.endLoop).includes(Number(this.changeBefore.endNumber)) &&  this.changeBefore.endNumber >= resultObj.endLoop &&  TestEnd > 1000) {
								const afterUp =Number(Math.floor(Math.round(TestEnd ) / 1000))
								const afterEnd = Math.round(Number(TestEnd % 1000))
								this.nextTick('endMileageFront', afterUp)
								this.nextTick('endMileageAfter', afterEnd)
								
								console.log('反向情况只需要计算结束里程', afterUp, afterEnd);
							}
						}
						this.$forceUpdate()
					}
				}

			},
			nextTick(key, row) {
				this.$nextTick(() => {
					if (typeof row != 'string') {
						row = String(row)
					}
					if (!!this.changeBefore[key]) {
						this.changeBefore[key] = row
					} else {
						this.$set(this.changeBefore, key, row)
					}
				})
			},
			chooseMileage() {
				if (this.ownerCode === 'hg') {
					this.isShowMileage = true
				}
			},
			sureMileage(e) {
				//同步修改父组件的值
				this.$emit('input', e.value[0])
				this.isShowMileage = false
			},
			// 删除文件
			closeFile(file, index) {
				console.log(file, index);
				if(file.uploadStatus) {
					return uni.showToast({
						title:'上传中,请稍后再试！',
						icon:'none',
						mask:true
					})
				}
				if (!this.changeBefore.removeFileSet) {
					this.changeBefore.removeFileSet = new Set()
				}
				if (file.id) {
					this.changeBefore.removeFileSet.add(file.id)
				}
				console.debug(this.changeBefore.removeFileSet, '===')
				this.changeBefore.videoFileList.splice(index, 1)
				// doDelete(deleteImg, {
				// 	id: file.id
				// }).then(res => {
				// 	console.log(res, 'shan')
				// 	if (!res.success) return uni.showToast({
				// 		title: '删除失败',
				// 		icon: "none"
				// 	})
				// 	this.changeBefore.videoFileList.splice(index, 1)
				// 	// uni.showToast({
				// 	// 	title: '删除成功',
				// 	// 	icon: "none"
				// 	// })
				// })
			},
			/** 预览文件 */
			handleClickPreview(item) {
				console.log(item, '点击视频');
				if (item.url.startsWith("_doc")) {
					item.url = 'file://' + plus.io.convertLocalFileSystemURL(item.url);
				}
				// 'http://www.w3cmap.com/try/demo_source/movie.mp4'
				this.playVideoSrc = item.url;
			},
			async clickMedias(e) {
				uni.chooseVideo({
					sourceType: ['camera', 'album'],
					maxDuration: 60,
					success: async res => {
						console.log(res, parseInt(res.duration), '选择成功回调函数');
						if (parseInt(res.duration) > 60) {
							return uni.showToast({
								title: '上传的视频不能超过60s',
								icon: 'none',
								mask: true
							})
						}
						this.changeBefore.videoFileList.push({
							url: res.tempFilePath,
							type: "video",
							uploadStatus:true
						})
						let fileList = [...this.changeBefore.videoFileList].filter(item => !item.id);
						for (let item of fileList) {
							let formData = {}
							if (this.changeBefore.videoDocId) {
								formData.docId = this.changeBefore.videoDocId
							}
							// #ifdef MP-WEIXIN
							const uploadResq = {
								url: "rest/doc/uploadDoc",
								formData,
								name: 'attach',
								filePath: item.url,
								isOffline: true
							}
							// #endif

							// #ifdef APP-PLUS || H5
							const uploadResq = {
								url: "rest/doc/uploadDoc",
								formData,
								files: [{
									name: "attach",
									uri: item.url
								}],
								isOffline: true
							}
							// #endif
							let data = await doSave(uploadFile, uploadResq)
							let res = data
							if (!res.success) return
							this.changeBefore.videoDocId = res.result.id
							console.log(this.changeBefore.videoDocId, '返回的id');
							const attachRes = await doGet(getPicture, {
								docId: this.changeBefore.videoDocId
							})
							console.log(attachRes, 'attachRes');
							if (attachRes.success && attachRes.result) {
								attachRes.result = attachRes.result.map(it => ({
									id: it.id,
									url: it.fileName ?
										this.$config.VIDEO_URL + it.fileName : it
										.url,
									uploadStatus:false
								}))
								this.$set(this.changeBefore, 'videoFileList', attachRes.result)
								this.changeBefore.updateVideoIds = this.changeBefore.videoFileList.map(i => i.id) || []
								this.changeBefore.videoFileList = this.changeBefore.videoFileList.filter(it => ![...this.changeBefore.removeFileSet].includes(it.id))
								console.error(this.changeBefore.videoFileList, '看看')
								console.debug(this.changeBefore.updateVideoIds,'更改后的视频id')
							}
						}
					},
					fail: (e) => {
						console.warn('错误', e);
					},
					complete: (end) => {
						// console.log(end);
					}
				});
			},

			/**
			 * @param {String} type
			 * 通过类型判断是现状还是修复措施
			 */
			getChooseType(type) {
				if (type === 'status') {
					this.changeBefore.diseaseGrade = undefined
					this.changeBefore.diseaseNo = undefined
					this.changeBefore.diseaseStandardLibraryId = undefined
				} else {
					this.changeBefore.diseaseMaterialId = undefined
				}
			},

			inputBlur(e, type) {
				// console.log('失焦事件')
				this.cursor = e.detail.cursor
				if (this.changeBefore.diseaseStatus) {
					this.getChooseType(type)
				}
			},

			// 滑块选择器
			swichChange1(e) {
				this.changeBefore.isSandySoil = e
			},
			swichChange2(e) {
				this.changeBefore.isInfluenceEquipment = e
			},
			swichChange3(e) {
				this.changeBefore.isProtectionSection = e
			},
			//录音事件
			fnDescription(text, type) {
				let index = this.cursor || 0
				let str = this.formData.description || ""
				this.cursor += text.length
				text = str.slice(0, index) + text + str.slice(index);
				if (type === 'status') {
					this.$set(this.changeBefore, "diseaseStatus", text)
				} else {
					this.$set(this.changeBefore, "repairMethod", text)
				}
			},
			// 打开时针位置选择器
			changtime() {

				if (this.ownerCode !== 'hg') {
					this.showTime = true
				} else {
					uni.navigateTo({
						url: '/subpackage-enginner/pages/engineeringMaintenance/common/selectClockwisePosition',
						//用于监听selectPeople页面发送过来的数据
						events: {
							setTimeEvent: (data) => {
								// console.log("点击时针位置", data.data)
								this.testTimeArr = data.data
								this.$set(this.changeBefore, 'clockwisePosition', data.data
									.map(r => r.name).join('、'))
								console.log(this.changeBefore.clockwisePosition);
							}
						},
						success: res => {
							console.log(this.compoType);
							console.log(this.changeBefore, '---');
							if (this.compoType === 'add') {
								let list = this.testTimeArr || []
								res.eventChannel.emit('getTimePosition', {
									data: list.map(item => item.id)
								})
							} else if (this.compoType === 'modify' || this.compoType ===
								'approval') {
								let result = this.changeBefore.clockwisePosition ? this
									.changeBefore.clockwisePosition.split("、") : []
								res.eventChannel.emit('getTimePosition', {
									data: result
								})
							}

						},
					});
				}

			},
			//时针位置取消选择
			cancel() {
				this.showTime = false
			},
			// 时针位置选择确定
			confirm(e) {
				console.log(e, '时针位置')
				this.changeBefore.clockwisePosition = e.value[0]
				this.showTime = false
			},
			//选择病害现状
			diseaseJs() {
				uni.navigateTo({
					url: `/subpackage-enginner/pages/engineeringMaintenance/on_site_inspection/components/dPresent?lineSiteSectionType=${this.lineSiteSectionType}`,
					events: {
						setData: (data) => {
							this.$set(this.changeBefore, 'diseaseStatus', data.data
								.diseaseStatus)
							this.$set(this.changeBefore, 'diseaseGrade', data.data
								.diseaseGrade)
							this.$set(this.changeBefore, 'diseaseGradeName', data.data
								.diseaseGrade)
							this.$set(this.changeBefore, 'diseaseGradeId', data.data
								.diseaseGradeId)
							this.$set(this.changeBefore, 'diseaseStandardLibraryId', data.data
								.id)
							this.$set(this.changeBefore, 'diseaseNo', data.data.diseaseNo)
							this.$set(this.changeBefore, 'rankClass', data.data.diseaseCode)
							console.log(this.changeBefore, '现状222222');
						}
					},
					success: res => {
						res.eventChannel.emit('getList', {
							data: 'data'
						})
					}
				})
			},
			inputVal(e, num) {
				if (num === 1) {
					this.$nextTick(() => {
						if (e != 0) {
							this.changeBefore.startMileageFront = e.replace(/^(0+)|[^\d]+/g, '')
						}
					})
				}
				if (num === 2) {
					this.$nextTick(() => {
						if (e != 0) {
							this.changeBefore.startMileageAfter = e.replace(/^(0+)|[^\d]+/g, '')
						}
					})
				}
				if (num === 3) {
					this.$nextTick(() => {
						if (e != 0) {
							this.changeBefore.startNumber = e.replace(/^(0+)|[^\d]+/g, '')
						}
					})
				}

			},
			changeVal(e, num) {
				if (num === 1) {
					this.changeBefore.endMileageFront = e.replace(/^(0+)|[^\d]+/g, '0')
				}
				if (num === 2) {
					this.changeBefore.endMileageAfter = e.replace(/^(0+)|[^\d]+/g, '0')
				}
				if (num === 3) {
					this.changeBefore.endNumber = e.replace(/^(0+)|[^\d]+/g, '0')
				}
			},

			/**删除图片*/
			deletePic(event) {
				console.log(event, '删除----');
				doDelete(deleteImg, {
					id: event.file.id
				}).then(res => {
					console.log(res, 'shan')
					if (!res.success) return uni.showToast({
						title: '删除失败',
						icon: "none"
					})
					this.changeBefore.fileListImg.splice(event.index, 1)
					// uni.showToast({
					// 	title: '删除成功',
					// 	icon: "none"
					// })
				})
			},
			/**新增图片
			 * @param {Object} event
			 */
			async afterRead(event) {
				// debugger
				this.isChooseImg = true
				for (let item in event.file) {
					this[`fileList${event.name}`].push({
						...event.file[item],
						status: 'uploading',
						message: '上传中'
					})
				}

				console.log(this.fileListImg, 'tempImgList')
				//1、通过上传接口获取水印图片的id
				let fileList = [...this.fileListImg]
				for (let item of fileList) {
					if (!item.status) continue
					let formData = {}
					//区间/站点
					formData.name = this.subTitleName
					//里程
					const distance = this.getContent2(this.changeBefore)
					//环号
					const startRing = this.changeBefore.startNumber || ''
					const endRing = this.changeBefore.endNumber || ''
					const others = this.changeBefore.others || ''
					const timeClock = this.changeBefore.clockwisePosition || ''
					formData.ring =
						`${distance}${distance && startRing ? ',' : ''}${startRing}${startRing && endRing ? '~' : '' }${endRing}${(distance && others)||(endRing && others) ? ',' : ''}${others}${(distance && timeClock)  ||  (startRing && endRing && timeClock) || (others&&timeClock)  ? ',' : ''}${timeClock}`
					//现状
					formData.status = this.changeBefore.diseaseStatus || ''
					formData.dateTime = this.getDate2(new Date)
					let arrList = [formData.name, formData.ring, formData.status, formData.dateTime]
					let isOwnerProjectId = uni.getStorageSync("isOwner")
					let resq_params = {
						token: getToken(),
						dataList: JSON.stringify(arrList),
						projectId: isOwnerProjectId
					}
					//通过index判断 避免图片id一直是同一个
					if (this.changeBefore.docId) {
						resq_params.docId = this.changeBefore.docId
					}
					//请求水印接口
					// #ifdef MP-WEIXIN
					const uploadImg = {
						url: "composite/picture/addPictureText",
						formData: resq_params,
						name: `file`,
						filePath: item.url,
						isOffline: true
					}
					// #endif

					// #ifdef APP-PLUS || H5
					const uploadImg = {
						url: "composite/picture/addPictureText",
						formData: resq_params,
						files: [{
							name: `file`,
							uri: item.url
						}],
						isOffline: true
					}
					// #endif
					let data = await doSave(uploadFile, uploadImg)
					console.log(data, '---------------data---------------');
					let res = data
					if (!res.success) {
						uni.showToast({
							title: '上传水印图片失败',
							icon: 'none'
						})
						this.isChooseImg = false
					} else {
						this.changeBefore.docId = res.result.id
						const attachRes = await doGet(getPicture, {
							docId: this.changeBefore.docId
						})
						console.log(attachRes, 'attachRes=======');
						if (attachRes.success && attachRes.result) {
							attachRes.result = attachRes.result.map(it => ({
								id: it.id,
								url: it.fileName ?
									this.$config.IMG_FILE_URL + it.fileName : it.url
							}))
							this.$set(this.changeBefore, 'fileListImg', attachRes.result)
							this.changeBefore.updateIds = this.changeBefore.fileListImg.map(i => i.id) || []
							console.debug(this.changeBefore.updateIds,'更改后的id')
							console.error(this.changeBefore.fileListImg);
							// debugger
						}
						
						// debugger
						this.isChooseImg = false
					}
				}
			},


			/**
			 * 校验表单必填
			 */
			validFormItem() {
				if (!this.changeBefore.diseaseStatus) {
					uni.showToast({
						title: '请选择病害现状',
						icon: 'none'
					})
					this.reqLoading = false
					return false
				}

				if (!this.changeBefore.diseaseGrade) {
					uni.showToast({
						title: '请选择病害等级',
						icon: 'none'
					})
					this.reqLoading = false
					return false
				}
				if (this.changeBefore.isInfluenceEquipment) {
					if (!this.changeBefore.deviceLocation) {
						uni.showToast({
							title: '请选择影响设备位置',
							icon: 'none'
						})
						this.reqLoading = false
						return false
					}

				}
				if (this.changeBefore.deviceLocation === '其他') {
					if (!this.changeBefore.inputValue) {
						uni.showToast({
							title: '请先填写输入框的值',
							icon: 'none'
						})
						this.reqLoading = false
						return false
					}
				}
				this.reqLoading = false
				return true
			},

			submit() {
				this.reqLoading = true
				// console.log(this.reqLoading)
				if (!this.validFormItem()) return
				// console.log(222222, this.lineInfo);
				if (this.lineInfo.lineSiteSectionType === 'cz') {
					if (!this.changeBefore.stationLocation && !this.changeBefore.others) {
						return uni.showToast({
							title: '位置选择和其他必填其一',
							icon: 'none'
						})
					}
					this.reqLoading = false
					// return
				}
				// debugger
				if (this.lineInfo.lineSiteSectionType !== 'qj' && this.lineInfo.lineSiteSectionType !==
					'cz') {
					if (!this.changeBefore.others) {
						return uni.showToast({
							title: '请填写位置',
							icon: 'none'
						})
					}
					this.reqLoading = false
					// return
				}
				this.$set(this.changeBefore, 'deviceLocation', this.changeBefore.inputValue ? this
					.changeBefore
					.inputValue + this.changeBefore.deviceLocation : this.changeBefore
					.deviceLocation)
				// console.log(this.changeBefore,this.value,'看看穿过的');
				this.$emit('addSubmit', this.changeBefore)

				// this.reqLoading = false
			},
			//病害审核通过按钮  第二个传参为是否通过
			passBtn() {
				if (!this.validFormItem()) return
				this.$set(this.changeBefore, 'deviceLocation', this.changeBefore.inputValue ? this
					.changeBefore
					.inputValue + this.changeBefore.deviceLocation : this.changeBefore
					.deviceLocation)
				this.$emit('passSubmit', this.changeBefore, true)
			},
			sureBtn() {
				// if(!this.validFormItem()) return
				this.$emit('passSubmit', this.changeBefore, false)
			},
			//现状回车按钮事件
			getDefineValue(val, type) {
				console.log(val, type, '1108adlaiadja',this.changeBefore)
				this.getChooseType(type)
			},
			//录音框清除事件
			clearTxt(val, type) {
				if (type === 'status') {
					this.changeBefore.diseaseStatus = ''
					this.isClickEnter = false
					this.changeBefore.diseaseGrade = undefined
					this.changeBefore.diseaseNo = undefined
					this.changeBefore.diseaseStandardLibraryId = undefined
				} else {
					this.changeBefore.repairMethod = ''
					this.changeBefore.diseaseMaterialId = undefined
				}
			},
			//选择病害等级
			fnChooseLevel() {
				this.getLevelOptions(uni.getStorageSync('isOwner'))
			},
			//获取病害等级选择项
			async getLevelOptions(projectId) {
				let resq = {
					currPage: 1,
					pageSize: 9999,
					params: {
						projectId
					}
				}
				let result1 = await doGet(XUNJIAN.diseaseGradeList, resq)
				let {
					list
				} = result1.result || []
				this.$set(this.levelColumns, 0, list)
				if (list.length > 0) {
					let result2 = await doGet(XUNJIAN.getDiseaseContent, {
						diseaseGradeId: this.selectedFirstId ? this.selectedFirstId : list[
							0].id,
						code: JSON.parse(uni.getStorageSync('lineData'))
							.lineSiteSectionType
					})
					// console.log(result2.result, '二级');
					//展示等级+编号
					this.levelColumns[1] = result2.result.map(it => ({
						...it,
						diseaseGrade: it.diseaseNo || '',
						diseaseNo: it.diseaseGrade || ''
					}))
					// console.log(this.levelColumns[1], '=======');
				}else{
					uni.showToast({
						title:'未配置病害等级',
						icon:'none',
						mask:true
					})
				}
				this.$forceUpdate()
			},
			fnMultiColumnChange(e) {
				if (!e.detail.column) {
					let idx = e.detail.value
					this.values = [e.detail.value, 0] // 区列表下标归零
					// console.log(this.values, 'values')
					doGet(XUNJIAN.getDiseaseContent, {
						diseaseGradeId: this.levelColumns[0][idx].id,
						code: JSON.parse(uni.getStorageSync('lineData'))
							.lineSiteSectionType
					}).then(res => {
						this.levelColumns[1] = res.result.map(it => ({
							...it,
							diseaseGrade: it.diseaseNo,
							diseaseNo: it.diseaseGrade
						})) // 设置多级联动区列表的值
						// console.log(this.levelColumns[1], '========滑动事件');
						this.$forceUpdate()
					})
				}
			},
			//picker确定后事件
			fnMultiPickerChange(e) {
				let _taskIdx = e.detail.value[0]
				//通过这个id查询第二列数据
				this.selectedFirstId = this.levelColumns[0][_taskIdx].id
				let _faceIdx = e.detail.value[1]
				let selectData = [this.levelColumns[0][_taskIdx], this.levelColumns[1][_faceIdx]]
				if (this.levelColumns[1][_faceIdx]) {
					this.$set(this.changeBefore, 'diseaseGrade', this.levelColumns[1][_faceIdx]
						.diseaseNo)
					this.$set(this.changeBefore, 'diseaseNo', this.levelColumns[1][_faceIdx]
						.diseaseGrade)
					this.$set(this.changeBefore, 'diseaseStandardLibraryId', this.levelColumns[1][
						_faceIdx
					].id)
					this.$set(this.changeBefore, 'diseaseGradeId', this.levelColumns[0][_taskIdx]
						.id)
					this.$set(this.changeBefore, 'diseaseGradeName', this.levelColumns[0][_taskIdx]
						.diseaseGrade)
					this.$set(this.changeBefore, 'rankClass', this.levelColumns[0][_taskIdx].code)
				} else {
					this.$set(this.changeBefore, 'diseaseGrade', this.levelColumns[0][_taskIdx]
						.diseaseGrade)
					// this.$set(this.changeBefore, 'diseaseStatus', this.levelColumns[0][_taskIdx].diseaseGrade)
					this.$set(this.changeBefore, 'diseaseNo', '')
					this.$set(this.changeBefore, 'diseaseGradeId', this.levelColumns[0][_taskIdx]
						.id)
					this.$set(this.changeBefore, 'diseaseGradeName', this.levelColumns[0][_taskIdx]
						.diseaseGrade)
					this.$set(this.changeBefore, 'diseaseStandardLibraryId', 0)
				}
				// console.log(this.changeBefore.diseaseStandardLibraryId, '----')
				this.$forceUpdate()
				this.isClickEnter = false
			},
			//取消事件
			fnlevelCancel() {
				// console.log(this.selectedFirstId, '-----');
			},
			chooseEquip(num) {
				if (num === 1) {
					this.isShowStation = true
				} else {
					this.isShowEquip = true
				}
			},
			/**
			 * @param {Object} num 类型 1车站 2影响设备位置
			 */
			sureEquip(num) {
				if (num === 1) {
					let obj = this.stationList.find(it => it.selectedIdx === this
						.currentStationItemIndex)
					if (!obj) return uni.showToast({
						title: '请先选择！',
						icon: 'none'
					})
					this.isShowStation = false
					this.changeBefore.stationLocation = obj.name
				} else {
					let obj = this.equipList.find(it => it.selectedIdx === this.currentItemIndex)
					if (!obj) return uni.showToast({
						title: '请先选择！',
						icon: 'none'
					})
					this.isShowEquip = false
					this.changeBefore.deviceLocation = obj.name
					this.changeBefore.inputValue = undefined
				}
			},
			cancelEquip(num) {
				if (num === 1) {
					this.isShowStation = false
					if (this.compoType === 'add') {
						this.changeBefore.stationLocation = undefined
						this.currentStationItemIndex = -1
					}
				} else {
					this.isShowEquip = false
					if (this.compoType === 'add') {
						this.changeBefore.deviceLocation = undefined
						this.currentItemIndex = -1
					}
				}

			},
			/**
			 * @param {Object} i   当前对象
			 * @param {Object} idx 下标
			 * @param {Object} num 类型 1车站 2影响设备位置
			 */
			clickItemBox(i, idx, num) {
				if (num === 1) {
					this.currentStationItemIndex = idx
				} else {
					this.currentItemIndex = idx
				}
				this.$set(i, 'selectedIdx', idx)
			},
			chooseRepair() {
				uni.navigateTo({
					url: "/subpackage-enginner/pages/engineeringMaintenance/common/table",
					events: {
						setData: (data) => {
							// console.log(data.data, '打印');
							this.$set(this.changeBefore, 'diseaseMaterialId', data.data
								.id)
							this.$set(this.changeBefore, 'repairMethod', data.data
								.makt)
						}
					}
				})

			}
		}
	}
</script>
<style lang="scss" scoped src="./ncDusease.scss">

</style>